<template>
  <div id="ai-question-page">
    <a-card class="card" :loading="isLoading">
      <title-component title-text="AI生成题目"></title-component>
      <token-num-component ref="tokenNumRef"></token-num-component>
      <div class="form-container">
        <a-form :model="generateForm" :rules="generateFormRules" ref="generateFormRef">
          <a-form-item field="questionDesc" hide-label validate-trigger="blur">
            <a-textarea v-model="generateForm.questionDesc" placeholder="请输入题目描述,(例：环境保护知识的相关题目，正确选项得10分，题目难度大一些...)" allow-clear
                        :maxlength="200"></a-textarea>
          </a-form-item>
          <a-form-item field="questionNum" hide-label validate-trigger="blur">
            <a-input-number v-model="generateForm.questionNum" placeholder="请输入题目数量" :max="20"
                            :min="1"></a-input-number>
          </a-form-item>
          <a-form-item field="optionNum" hide-label validate-trigger="blur">
            <a-input-number v-model="generateForm.optionNum" placeholder="请输入选项数量" :max="8"
                            :min="1"></a-input-number>
          </a-form-item>
          <a-form-item field="model" hide-label validate-trigger="blur">
            <a-tooltip content="选择一个大模型" background-color="#3491FA">
              <a-select v-model="generateForm.model" placeholder="请选择模型"
                        style="width: 100%;">
                <a-option v-for="item in modelOptions" :key="item.value" :value="item.value">{{
                    item.label }}</a-option>
              </a-select>
            </a-tooltip>
          </a-form-item>
          <a-form-item hide-label>
            <a-button v-if="questions.length === 0" type="primary" long @click="onClickGenerate" :loading="isGenerating"
                      :disabled="isGenerating">生成
            </a-button>
            <a-button v-else type="primary" long @click="onClickGenerate" :loading="isGenerating"
                      :disabled="isGenerating">继续生成
            </a-button>
            <a-button type="primary" long style="margin-left: 10px;" :disabled="questions.length === 0 || isGenerating"
                      @click="onClickSaveGenerate"
            >
              保存
            </a-button>
          </a-form-item>
        </a-form>
      </div>
      <div v-if="isGenerating && questions.length === 0" class="question-result">
        <p>生成中，请稍候...</p>
      </div>
      <a-list v-if="questions.length > 0" class="question-result" size="small">
        <a-list-item v-for="(question, index) in questions" :key="index">
          <a-card size="small">
            <div class="title">
              {{ `${index + 1}. ${question.title}` }}
            </div>
            <div class="question-content" :style="{ 'word-break': 'break-all' }">
              <div v-for="option in question.options" :key="option.key" class="option-item">
                选项：{{ option.key }}. 选项内容：{{ option.value }}, 结果集合：{{ option.result }}, 得分：{{
                  option.score
                }}
              </div>
            </div>
          </a-card>
          <div v-if="isGenerating && index === questions.length - 1" class="loading-item">
            <a-spin dot tip="正在生成中..."></a-spin>
          </div>
        </a-list-item>
      </a-list>
    </a-card>
  </div>
</template>

<script setup>
import {ref, onMounted} from "vue";
import TitleComponent from "@/components/TitleComponent.vue";
import router from "@/router/index.js";
import TokenNumComponent from "@/components/TokenNumComponent.vue";
import {Message, Notification} from "@arco-design/web-vue";
import {useUserStore} from "@/stores/index.js";
import {EventSourcePolyfill} from "event-source-polyfill";
import {saveGenerateQuestionByAppId} from "@/api/question.js";
import {BASE_URL} from "@/utils/request.js";

const generateForm = ref({
  appId: null,
  questionDesc: "",
  questionNum: null,
  optionNum: null,
  model: 625,
  platform: 0
});

const generateFormRules = {
  questionDesc: [
    {required: true, message: "请输入题目描述", trigger: "blur"},
    {max: 200, message: "题目描述长度不能超过200字", trigger: "blur"},
  ],
  questionNum: [
    {required: true, message: "请输入题目数量", trigger: "blur"},
    {type: "number", min: 1, max: 20, message: "题目数量范围为1 - 20", trigger: "blur"},
  ],
  optionNum: [
    {required: true, message: "请输入选项数量", trigger: "blur"},
    {type: "number", min: 1, max: 8, message: "选项数量范围为1 - 8", trigger: "blur"},
  ],
  model: [
    {required: true, message: "请选择模型", trigger: "blur"},
  ]
};

const modelOptions = [
  {
    label: "DeepSeek-v3",
    value: 917,
  },
  {
    label: "DouBao-Pro-32k",
    value: 420,
  },
  {
    label: "ChatGLM4",
    value: 625,
  },
  {
    label: "ChatGLM4v",
    value: 331,
  },
];
const platformListOfZhiPu = ref([
  625,
  331
])

const platformListOfVolcano = ref([
  917,
  420
])

const generateFormRef = ref();
const isLoading = ref(false);
const questions = ref([]);
const isGenerating = ref(false);
const tokenNumRef = ref();

onMounted(() => {
  generateForm.value.appId = router.currentRoute.value.params.id;
});

/**
 * 使用 EventSourcePolyfill 实现 SSE 题目生成
 */
const onClickGenerate = async () => {
  if (questions.value.length > 50) {
    Message.warning("已达到最大生成题目数量")
    return
  }
  if (generateForm.value.model === null) {
    Message.warning("请选择模型")
    return
  }
  if (generateForm.value.platform === null) {
    Message.warning("请选择平台")
    return
  }
  if (platformListOfZhiPu.value.includes(generateForm.value.model)) {
    generateForm.value.platform = 0
  }
  if (platformListOfVolcano.value.includes(generateForm.value.model)) {
    generateForm.value.platform = 1
  }
  await generateFormRef.value.validate(async (valid) => {
    if (!valid) {
      Message.info('AI生成中请勿离开界面')
      isGenerating.value = true;
      // 获取用户 Token
      const userStore = useUserStore();
      const token = userStore.token;

      // 构造 SSE 请求 URL
      const url = `${BASE_URL}/user/question/ai`;

      // 创建 EventSourcePolyfill 实例
      const eventSource = new EventSourcePolyfill(
        url +
        `?appId=${generateForm.value.appId}&questionDesc=${generateForm.value.questionDesc}&questionNum=${generateForm.value.questionNum}&optionNum=${generateForm.value.optionNum}&model=${generateForm.value.model}&platform=${generateForm.value.platform}`,
        {
          headers: {
            Authorization: token, // 设置自定义请求头
          },
        }
      );

      // 监听消息事件
      eventSource.onmessage = (event) => {
        try {
          if (event.data === "EventFinnish") {
            Notification.success({
              title: "提示",
              content: "题目全部生成成功",
              duration: 5000,
              closable: true,
            });
            eventSource.close();
            isGenerating.value = false;
            tokenNumRef.value.getUserTokenNum()
          } else {
            const data = JSON.parse(event.data); // 解析服务器推送的数据
            questions.value.push(data); // 将新题目添加到列表中
          }
        } catch (error) {
          console.error("解析 SSE 数据失败:", error);
        }
      };

      // 监听错误事件
      eventSource.onerror = () => {
        console.error("SSE 连接出错");
        Message.error("生成失败,请稍后重试");
        eventSource.close(); // 关闭连接
        isGenerating.value = false;
      };

      // 监听关闭事件
      eventSource.onclose = () => {
        console.log("SSE 连接已关闭");
      };
    }
  });
};

const onClickSaveGenerate = () => {
  if (generateForm.value.appId ===null){
    Message.error('应用id错误，请刷新页面')
    return
  }
  if (questions.value.length === 0) {
    Message.warning('未生成题目')
    return
  }
  const formData = {
    appId: generateForm.value.appId,
    questionContent: questions.value,
  };
  saveGenerateQuestionByAppId(formData)
    .then((response) => {
      if (response.data.code === 1) {
        Message.success('保存成功')
        router.back()
      } else {
        Message.error('保存失败，请重试')
      }
    })
    .catch((error) => {
      console.error('保存失败：', error);
    })
}
</script>

<style scoped>
.card {
  margin-top: 20px;
}

.form-container {
  margin-top: 20px;
  width: 50%;
}

.question-result {
  margin-top: 20px;
}

.question-content {
  font-size: 16px;
}

.title {
  color: var(--color-text-1);
  font-size: 18px;
}

.option-item {
  background-color: var(--color-bg-3);
  font-size: 14px;
}

.loading-item {
  margin-top: 10px;
  text-align: center;
}

@media (max-width: 768px) {
  .form-container {
    width: 100%;
  }
}
</style>
